package com.currency.simulation;

import java.util.Random;

public class Generator implements Runnable
{
	private static Generator myGenerator = null;
	private boolean generating;
	private Thread myThread;
	private Random random;
	private NewEntryHandler handler;
	
	private Generator()
	{
		generating = false;
		random = new Random();
	}
	
	public static Generator getInstance()
	{
		if(myGenerator == null)
		{
			myGenerator = new Generator();
		}
		
		return myGenerator;
	}
	
	public void startGenerating(NewEntryHandler neh)
	{
		handler = neh;
		generating = true;
		myThread = new Thread(this);
		myThread.start();
	}
	
	@Override
	public void run()
	{
		int i = 0;
		while(generating && i < 20)
		{
			try
			{
				int nextInt = random.nextInt(1000);
				handler.handleNewEntry(nextInt);
				
				Thread.sleep(nextInt);
				i++;
			}
			catch(InterruptedException ie)
			{
				System.out.println("Error occured.");
			}
		}
	}
}
